<template>
  <div class="container">
    <el-card v-loading="loading">
      <div class="box">
        <div style="color:pink">说明：目前支持学科和关键字条件筛选</div>
       <div> <el-button type="success"  icon="el-icon-edit" @click="$router.push('/questions/new')">新增试题</el-button></div>
      </div>
      <el-form  :model="formInline" class="demo-form-inline">
        <!-- 第一行 -->
        <el-row>
          <el-col :span="6">
            <el-form-item label="学科">
              <el-select v-model="formInline.subject"  @change="getDirectoryAndTags" placeholder="请选择">
                <el-option :label="item.label" :value="item.value" v-for="item in simpleSubjectList" :key="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="二级目录">
              <el-select  v-model="formInline.catalog" placeholder="请选择">
                <el-option :label="item.directoryName" :value="item.id" v-for="item in directoryList.items" :key="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标签">
              <el-select v-model="formInline.tags" placeholder="请选择">
               <el-option :label="item.tagName" :value="item.id" v-for="item in tagsList" :key="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关键字">
              <el-input
                v-model="formInline.keyword"
                placeholder="根据题干搜索"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row>
          <el-col :span="6">
            <el-form-item label="试题类型">
              <el-select v-model="formInline.questionType" placeholder="请选择">
                 <el-option :label="item.value" :value="item.id" v-for="item in questionType" :key="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="难度">
              <el-select v-model="formInline.difficulty" placeholder="请选择">
                <el-option :label="item.value" :value="item.id" v-for="item in level" :key="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="方向">
              <el-select v-model="formInline.direction" placeholder="请选择">
                <el-option :label="item" :value="item" v-for="item in direction" :key="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="录入人">
              <el-select @focus="getUserList" v-model="formInline.creator" placeholder="请选择">
                 <el-option :label="item.username" :value="item.id" v-for="item in userList" :key="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行 -->
        <el-row>
          <el-col :span="6">
            <el-form-item label="题目备注">
              <el-input v-model="formInline.remarks"
                placeholder="根据题干搜索"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="企业简称">
              <el-input
                v-model="formInline.shortName"
                placeholder="根据题干搜索"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item style="margin-right: 48px" label="城市">
              <el-row>
                <el-col :span="12">
                  <el-select  @change="getCity($event)" v-model="formInline.province" placeholder="请选择">
                    <el-option :label="item" :value="item" v-for="item in provinces" :key="item">
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="12">
                  <el-select  v-model="formInline.city" placeholder="请选择">
                    <el-option :label="item" :value="item" v-for="item in cityList" :key="item">
                    </el-option>
                  </el-select>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <!-- 清除 搜索  --------  按钮 -->
          <el-col :span="6">
            <el-form-item>
                  <el-button  style="margin-left: 136px" @click="clearForm">清除</el-button>
                  <el-button type="primary" @click="onSubmit">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- info 提示框 -->
      <el-alert
        :title="`数据一共${counts}条`"
        type="info"
        :closable="false"
        show-icon>
      </el-alert>

      <!-- 下方表格 -->
      <el-table
       v-loading="loading"
        :data="tableData"
        style="width: 100%">
        <el-table-column label="试题编号" prop="number" width="120">
          <template #default="{row}">{{row.number}}</template>
        </el-table-column>
        <el-table-column label="学科" prop="subject">
          <template #default="{row}">{{row.subject}}</template>
          <!-- <template #default="{row}">{{formatSubject(row.subjectID)}}</template> -->
        </el-table-column>
        <el-table-column label="目录" prop="catalog" >
          <template #default="{row}">{{row.catalog}}</template>
        </el-table-column>
        <el-table-column label="题型" prop="questionType">
          <template #default="{row}">{{formatQuestionType(row.questionType)}}</template>
        </el-table-column>
        <el-table-column prop="question" label="题干" width="280">
          <template #default="{row}">
            <div v-html="row.question"></div>
          </template>
        </el-table-column>
        <el-table-column prop="addDate" label="录入时间" width="180">
          <template #default="{row}">{{formatDate(row.addDate)}}</template>
        </el-table-column>
        <el-table-column prop="difficulty" label="难度">
          <template #default="{row}">{{formatLevel(row.difficulty)}}</template>
        </el-table-column>
        <el-table-column prop="creator" label="录入人">
          <template #default="{row}">{{row.creator}}</template>
        </el-table-column>
        <el-table-column label="操作"  width="180">
          <template #default="{row}">
            <el-button size="mini" plain type="primary" icon="el-icon-view" circle @click="handleView(row)"></el-button>
            <el-button size="mini" plain  type="success" icon="el-icon-edit" circle @click="$router.push(`/questions/new?id=${row.id}`)"></el-button>
            <el-button size="mini" plain type="danger" icon="el-icon-delete" circle @click="handleDelete(row)"></el-button>
            <el-button size="mini" plain type="warning" icon="el-icon-check" circle @click="handleOk(row)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
       <el-pagination
        style="margin-top: 20px;"
        background
        layout="-> , prev, pager, next, sizes , jumper"
        :total="counts"
        :page-sizes="[1, 2, 5, 10]"
        :current-page="page"
        :page-size="pagesize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        >
      </el-pagination>
    </el-card>

    <!-- dialog -->
    <el-dialog v-loading="loading" title="题目预览" @close="closeDialog" :visible="dialogVisible">
      <el-descriptions class="margin-top" :column="4">
        <el-descriptions-item label="【题型】">{{formatQuestionType(questionDetail2.questionType)}}</el-descriptions-item>
        <el-descriptions-item label="【编号】">{{questionDetail2.number}}</el-descriptions-item>
        <el-descriptions-item label="【难度】">{{difficulty}}</el-descriptions-item>
        <el-descriptions-item label="【标签】">{{questionDetail2.tags}}</el-descriptions-item>
        <el-descriptions-item label="【学科】">{{questionDetail2.subjectName}}</el-descriptions-item>
        <el-descriptions-item label="【目录】">{{formatDirectory(questionDetail2.catalogID)}}</el-descriptions-item>
        <el-descriptions-item label="【方向】">{{questionDetail2.direction}}</el-descriptions-item>
      </el-descriptions>
      <!-- 题干 -->
      <el-divider></el-divider>
       <el-descriptions class="margin-top"  direction="vertical">
        <el-descriptions-item label="【题干】">
          <div v-html="questionDetail2.question"></div>

          <!-- 单选 -->
          <div v-if="flag === '1'">
            <div>{{questionDetail.questionType}} 选项：(以下选中的选项为正确答案)</div>
            <el-radio-group v-model="radioChioce">
              <el-radio :label="item.code" v-for="item in questionDetail.options" style="display:block;margin-top:15px" :key="item.id">
                {{item.title}}
             </el-radio>
            </el-radio-group>
          </div>

          <!-- 多选 -->
         <div v-else-if="flag === '2'">
            <div>{{questionDetail.questionType}} 选项：(以下选中的选项为正确答案)</div>
            <el-checkbox-group v-model="checkoutChioce">
              <el-checkbox  :label="item.code" v-for="item in questionDetail.options" style="display:block;margin-top:15px" :key="item.id">
                {{item.title}}
              </el-checkbox>
            </el-checkbox-group>
         </div>

         <!-- 简答 -->
         <div v-else></div>
        </el-descriptions-item>
      </el-descriptions>
      <!-- 参考答案 -->
      <el-divider></el-divider>
       <el-descriptions class="margin-top" :column="1">
        <el-descriptions-item label="【参考答案】">
          <el-button @click="isShowVideo" type="danger">视频答案预览 </el-button>
        </el-descriptions-item>
      </el-descriptions>
          <!-- 视频标签 -->
      <video v-if="showVideo" controls height=240 :src="questionDetail.videoURL"></video>
       <!-- 答案解析 -->
      <el-divider></el-divider>
       <el-descriptions class="margin-top" :column="1">
        <el-descriptions-item label="【答案解析】">{{questionDetail.answerID}}</el-descriptions-item>
      </el-descriptions>
       <!-- 题目备注 -->
      <el-divider></el-divider>
       <el-descriptions class="margin-top" :column="1">
        <el-descriptions-item label="【题目备注】">{{questionDetail.remarks}}</el-descriptions-item>
      </el-descriptions>
      <el-divider></el-divider>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { list as reqUserList } from '@/api/base/users'
import { list, detail, remove, choiceAdd } from '@/api/hmmm/questions'
import { simple } from '@/api/hmmm/subjects'
import { simple as directorysSimple, list as reqdirectoryList } from '@/api/hmmm/directorys'
import { list as reqtagsList } from '@/api/hmmm/tags'
import { direction } from '@/api/hmmm/constants'
import { provinces, citys } from '@/api/hmmm/citys'
import dayjs from 'dayjs'
export default {
  name: 'Questions',
  data () {
    return {
      direction,
      provinces: provinces(),
      flag: '',
      page: 1,
      pagesize: 5,
      radioChioce: '',
      checkoutChioce: [],
      loading: false,
      showVideo: false,
      dialogVisible: false,
      simpleSubjectList: [],
      directorysSimpleList: [],
      directoryList: [],
      tagsList: [],
      userList: [],
      cityList: [],
      formInline: {
        subject: '',
        catalog: '',
        tags: '',
        keyword: '',
        questionType: '',
        difficulty: '',
        direction: '',
        creator: '',
        remarks: '',
        shortName: '',
        province: '',
        city: ''
      },
      tableData: [],
      questionDetail: {},
      questionDetail2: {},
      counts: 0,
      level: [{ id: 1, value: '简单' }, { id: 2, value: '一般' }, { id: 3, value: '困难' }],
      questionType: [{ id: '1', value: '单选' }, { id: '2', value: '多选' }, { id: '3', value: '简答' }]
    }
  },
  async created () {
    // await this.getSimpleSubjectList()
    // await this.getDirectorysSimple()
    this.getQuestionsList()
  },
  computed: {
    difficulty () {
      return this.level.find(item => item.id === +this.questionDetail.difficulty)?.value || ' '
    }
  },
  methods: {
    clearForm () {
      // this.$refs.formRef.resetFields()
      this.formInline = {
        subject: '',
        catalog: '',
        tags: '',
        keyword: '',
        questionType: '',
        difficulty: '',
        direction: '',
        creator: '',
        remarks: '',
        shortName: '',
        province: '',
        city: ''
      }
      this.directoryList = []
      this.tagsList = []
      this.cityList = []
      this.page = 1
    },
    async onSubmit () {
      if (this.formInline.subject && this.formInline.keyword) {
        const data = this.tableData.filter(item => {
          return (item.subject === this.formInline.subject) && (item.keyword === this.formInline.keyword)
        })
        // console.log(data)
        this.page = 1
        this.pagesize = data.length
        this.tableData = data
      }
      if (this.formInline.subject && !this.formInline.keyword) {
        // console.log(this.formatSubject(this.formInline.subject))
        const data = this.tableData.filter(item => {
          return item.subject === this.formatSubject(this.formInline.subject)
        })
        this.page = 1
        this.pagesize = data.length
        this.tableData = data
      }
      if (this.formInline.keyword && !this.formInline.subject) {
        // console.log(this.formInline.keyword)
        const data = this.tableData.filter(item => {
          return item.keyword === this.formInline.keyword
        })
        this.page = 1
        this.pagesize = data.length
        this.tableData = data
      }
      if (!this.formInline.subject && !this.formInline.keyword) {
        this.getQuestionsList()
      }
      // this.page = 1
      // console.log(this.formInline)
      // const { data } = await list(this.formInline)
      // console.log(data)
    },
    radioChiocefn () {
      const aa = this.questionDetail.options.filter(item => item.isRight === 1)
      if (!aa[0]?.code) return []
      return aa[0].code
    },
    checkoutChiocefn () {
      const aa = this.questionDetail.options.filter(item => item.isRight === 1)
      const bb = []
      aa.forEach(item => {
        bb.push(item.code)
      })
      //  if () return []
      return bb
    },
    // 每页多少条
    handleSizeChange (val) {
      this.pagesize = val
      this.page = 1
      this.getQuestionsList()
    },
    // 第几页
    handleCurrentChange (val) {
      this.page = val
      this.getQuestionsList()
    },
    // 处理时间
    formatDate (time) {
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
    },
    // 处理难度
    formatLevel (num) {
      return this.level.find(item => item.id === +num)?.value || ' '
    },
    // 处理题型
    formatQuestionType (str) {
      return this.questionType.find(item => item.id === str)?.value || ' '
    },
    // 处理学科
    formatSubject (num) {
      // console.log(num)
      return this.simpleSubjectList.find(item => +item.value === +num)?.label || ' '
    },
    // 处理目录
    formatDirectory (num) {
      return this.directorysSimpleList.find(item => item.value === num)?.label || ' '
    },
    // 获取题目列表
    async getQuestionsList () {
      this.loading = true
      await this.getSimpleSubjectList()
      await this.getDirectorysSimple()
      const { data } = await list({ page: this.page, pagesize: this.pagesize })
      // console.log(data.items)
      // data.items.forEach(item => {
      // item.subjectID = this.formatSubject(item.subjectID)
      //   item.catalogID = this.formatDirectory(item.catalogID)
      //   item.addDate = this.formatDate(item.addDate)
      //   item.difficulty = this.formatLevel(item.difficulty)
      //   item.questionType = this.formatQuestionType(item.questionType)
      // })
      this.counts = data.counts
      this.tableData = data.items
      // console.log(this.tableData)
      this.loading = false
      // console.log(data)
    },
    // 获取学科简单列表
    async getSimpleSubjectList () {
      const { data } = await simple({})
      this.simpleSubjectList = data
    },
    // 获取目录简单列表
    async getDirectorysSimple () {
      const { data } = await directorysSimple({})
      this.directorysSimpleList = data
    },
    // 获取二级目录 获取标签
    async getDirectoryAndTags () {
      const { data } = await reqdirectoryList({ subjectID: this.formInline.subject })
      this.directoryList = data
      console.log(this.directoryList)
      const { data: { items } } = await reqtagsList({ subjectID: this.formInline.subject })
      this.tagsList = items
    },
    // 获取后台用户列表
    async getUserList () {
      const { data: { list } } = await reqUserList({})
      this.userList = list
    },
    // 获取地区
    getCity (val) {
      const data = citys(val)
      this.cityList = data
    },
    closeDialog () {
      this.dialogVisible = false
      this.showVideo = false
      this.questionDetail = {}
    },
    isShowVideo () {
      if (this.questionDetail.videoURL === null || this.questionDetail.videoURL === '') return
      // console.log(this.questionDetail, '111212')
      // if (this.questionDetail.subjectName)
      this.showVideo = !this.showVideo
    },
    // 预览
    async handleView (row, str) {
      this.dialogVisible = true
      this.loading = true
      // if ((row.options && row.options.length === 0) || !row.options) {
      // this.flag = ''
      // }
      // if (row.options.length > 0) {
      this.flag = str
      this.questionDetail2 = row
      // }
      // console.log(this.simpleSubjectList)
      // console.log(row)
      if (row.subject === null || row.subject === '') {
        row.subject = ' '
        row.subjectName = row.subject
      }
      try {
        const { data } = await detail({ id: row.id })
        // console.log(row, data)
        this.questionDetail = data
        this.flag = this.questionDetail.questionType
        if (row.questionType === '1' || row.questionType === '2') {
          this.radioChioce = this.radioChiocefn()
          this.checkoutChioce = this.checkoutChiocefn()
        }
      } catch (error) {
        // console.log(error)
      }
      // this.questionDetail.difficulty = this.formatLevel(this.questionDetail.difficulty)
      // this.questionDetail.questionType = this.formatQuestionType(this.questionDetail.questionType)
      this.loading = false
    },
    // 点击删除
    handleDelete (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await remove(row)
        this.getQuestionsList()
        this.$message.success('删除成功')
      }).catch(() => {
      })
    },
    // 加入精选题库
    handleOk (row) {
      this.$confirm('此操作将该题目加入题库, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        row.choiceState = 1
        // console.log(row)
        await choiceAdd(row)
        this.$message.success('加入精选题库成功')
        this.$router.push('/questions/choice')
      }).catch(() => {
      })
    }
  }
}
</script>

<style scoped lang='less'>
::v-deep{
  .el-form-item {
  // display: inline-block !important;
  margin-right: 0 !important;
  }
  .el-form-item__label {
    // display: none;
    // width: 0px !important;
    position: absolute;
    margin-left: 20px;
  }
  .el-form-item__content {
    // margin-left: 3px !important;
    // margin-right: 3px !important;
    width: 100%;
    padding-left: 80px;
  }
  .el-select,
  .el-input_inner{
    width: 100%;
  }
  // .data-v-40019310.el-form-item.el-form-item--medium{
  //   position: relative;
  // }
}
.box{
  line-height: 100px;
  display: flex;
  justify-content: space-between;
}
</style>
